import { contextBridge, ipcRenderer } from 'electron'
import { electronAPI } from '@electron-toolkit/preload'

// Custom APIs for renderer
const api = {
  // 登录
  login: (loginId: string, loginKey: string) => ipcRenderer.invoke('login', loginId, loginKey),
  // 保存应用配置
  saveAppConfig: (key: string, value: unknown) => ipcRenderer.invoke('save-app-config', key, value),
  // 获取应用配置
  getAppConfig: (key: string) => ipcRenderer.invoke('get-app-config', key),
  // 打开外部链接
  openExternal: (url: string) => ipcRenderer.invoke('open-external', url)
}

// Use `contextBridge` APIs to expose Electron APIs to
// renderer only if context isolation is enabled, otherwise
// just add to the DOM global.
if (process.contextIsolated) {
  try {
    contextBridge.exposeInMainWorld('electron', electronAPI)
    contextBridge.exposeInMainWorld('api', api)
  } catch (error) {
    console.error(error)
  }
} else {
  // @ts-ignore (define in dts)
  window.electron = electronAPI
  // @ts-ignore (define in dts)
  window.api = api
}
